package com.my.controller;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.map.MapUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.api.R;
import com.my.domain.entity.Systematic;
import com.my.domain.entity.User;
import com.my.domain.vo.LoginVO;
import com.my.enums.ResultEnum;
import com.my.result.Result;
import com.my.service.SystematicService;
import com.my.service.UserService;
import com.my.utils.JwtToken;
import com.my.utils.JwtUtils;
import org.apache.catalina.security.SecurityUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;

/**
 * package:
 * author:
 * date:
 */
@RestController
public class AccountController {

    @Autowired
    UserService userService;

    @Autowired
    JwtUtils jwtUtils;
    @Autowired
    RedisTemplate redisTemplate;
    @Autowired
    SystematicService systematicService;

    @PostMapping("/login")
    public Result login(@Validated @RequestBody LoginVO loginVO, HttpServletResponse response){
        //
        //System.out.println("================AccountController类的46行执行login方法========================================================");
        //从数据库中获取该用户，通过用户名
        User user = userService.getOne(new LambdaQueryWrapper<User>().eq(User::getAccountName, loginVO.getAccountName()));
        Assert.notNull(user,"用户不存在");

        //Subject subject = SecurityUtils.getSubject();//获取当前用户
        String jwt = jwtUtils.generateToken(user.getId());//使用jwt工具类生成jwt
        //JwtToken jwtToken = new JwtToken(jwt);


        //SecureUtil.md5加密解密
        if (!user.getAccountPassword().equals(SecureUtil.md5(loginVO.getAccountPassword())  )){
            return Result.fail("密码错误");
        }
        Systematic systematic=systematicService.getById(1l);
        redisTemplate.opsForValue().set("systematic:LookNumber",systematic.getSystematicNum()+1);
        systematic.setSystematicNum(systematic.getSystematicNum()+1);
        systematicService.updateById(systematic);
        //否则登录成功,
//        String jwt = jwtUtils.createJWT(user.getId());
        //一般可以把jwt放在header里面
        System.out.println("把生成的jwt放入请求头中返回给前端");
        response.setHeader("Authorization", jwt);
        response.setHeader("Access-control-Expose-Headers", "Authorization");
        //返回，
        System.out.println("============"+jwt);
        return Result.okResult(MapUtil.builder()
                .put("id", user.getId())
                .put("username", user.getAccountName())
                .map()
        );

    }

    //退出接口
    @RequiresAuthentication
    @GetMapping("/logout")
    public Result logout() {
        //shiro进行退出
        SecurityUtils.getSubject().logout();
        return Result.okResult(null);
    }
}
